﻿using System;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;

namespace Artech.PetShop.Infrastructures
{
    public class PolicyInjectionPolicy : IPolicyInjectionPolicy, IBuilderPolicy
    {
        private static volatile PolicyInjectionHelper defaultHelper;
        private static readonly object singletonLock = new object();

        public IUnityContainer Container
        { get; private set; }

        public PolicyInjectionPolicy(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            this.Container = container;
        }


        private PolicyInjectionHelper GetHelperFromConfig(IConfigurationSource configurationSource)
        {
            return new PolicyInjectionHelper(configurationSource, this.Container);
        }

        private PolicyInjectionHelper DefaultHelper
        {
            get
            {
                if (defaultHelper == null)
                {
                    lock (singletonLock)
                    {
                        if (defaultHelper == null)
                        {
                            defaultHelper = GetHelperFromConfig(ConfigurationSourceFactory.Create());
                        }
                    }
                }
                return defaultHelper;
            }
        } 

        #region IPolicyInjectionPolicy Members

        public object ApplyProxy(object instanceToProxy, Type typeToProxy)
        {
           return DefaultHelper.Wrap(instanceToProxy, typeToProxy);
        }

        #endregion
    }
}